//
//  HMNetworkTools.swift
//  03 swift网络框架的封装
//
//  Created by 崔正强 on 17/3/27.
//  Copyright © 2017年 崔正强. All rights reserved.
//

import UIKit
//声明枚举
enum  HTTPMethod: Int {
    case GET
    case POST
}

import AFNetworking

class HMNetworkTools: AFHTTPSessionManager {

    //单例对象
    static let shared: HMNetworkTools = {
        let tools = HMNetworkTools()
        //设置支持的解析数据的类型
//        tools.responseSerializer = AFHTTPResponseSerializer()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tools
    }()
    
    /*
     
     - (void)request:(HTTPMethod)method url:(NSString *)urlString paramters:(id)paramters finished:(void (^)(id, NSError *))finished
     */
    //封装网络请求的核心方法
    func request(method: HTTPMethod, urlString: String, paramters: Any?, finished:@escaping (Any?, Error?) -> ()) {
        
        //定义闭包对象
        let success = { (task: URLSessionDataTask, responseObject: Any?) -> () in
            //执行成功回调
            print(responseObject!)
            finished(responseObject, nil)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) -> ()in
            //执行失败回调
            print(error)
            finished(nil,error)
        }
        
        
        if method == .POST {
            //post请求
            post(urlString, parameters: paramters, progress: nil, success: success, failure: failure)
        }
        
        if method == .GET {
            //get请求
            get(urlString, parameters: paramters, progress: nil, success: success, failure: failure)
        }
    }
}

//微博首页请求数据
extension HMNetworkTools{
    
    func homeLoadData(finished: @escaping (Any? , Error?) -> ()){
        
        //请求URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //请求参数
        let paras = ["access_token": HMUserAccountViewModel.shared.accessToken!]
        
        //发送请求
        request(method: HTTPMethod.GET, urlString: urlString, paramters: paras, finished: finished)
    }
}
